package com.feilong.modules.controller.home;

import com.feilong.modules.common.constant.UploadConstant;
import com.feilong.modules.common.exception.APIException;
import com.feilong.modules.model.home.request.UpdateSwiperRequest;
import com.feilong.modules.model.home.vo.SwiperInfoVO;
import com.feilong.modules.service.home.HomeInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RefreshScope
@RequestMapping("home/info")
public class HomeInfoController {

    @Resource
    private HomeInfoService homeInfoService;

    /**
     * 从云开发数据库获取首页轮播图信息
     * @return
     */
    @GetMapping("swiper/list")
    public List<SwiperInfoVO> getSwiperList(){
        return homeInfoService.getSwiperList();
    }

    /**
     * 根据轮播图id更新云开发数据库信息
     * @param request
     */
    @PostMapping("swiper/update")
    public void updateSwiper(@RequestBody @Valid UpdateSwiperRequest request) {
        homeInfoService.updateSwiper(request);
    }

    /**
     * 上传图片到微信云开发服务器
     * 上传后返回图片链接
     * @return
     */
    @PostMapping("uploadImage")
    public String uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer type, @RequestParam("fileName") String fileName) {
        if (type == null || StringUtils.isBlank(fileName) || file.isEmpty()) {
            throw new APIException(UploadConstant.UPLOAD_FAIL);
        }
        return homeInfoService.uploadImage(file, type, fileName);
    }
}
